package com.atguigu.system.utils;

import com.atguigu.model.system.SysMenu;
import lombok.val;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {
    /**
     * 构建树形
     *
     * @param sysMenus
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenus) {
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            //找到递归入口,parentId=0
            if (sysMenu.getParentId().longValue() == 0) {
                trees.add(findChildren(sysMenu, sysMenus));
            }
        }
        return trees;
    }

    /**
     * 从根节点进行递归查询子节点
     * id==parentId是否相同，相同就是子节点，进行数据封装
     *
     * @param sysMenu
     * @param treeNodes
     * @return
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> treeNodes) {
        //数据初始化
        sysMenu.setChildren(new ArrayList<>());
        for (SysMenu it : treeNodes) {
            val id = sysMenu.getId();
            if (Long.parseLong(id) == it.getParentId()) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return sysMenu;
    }
}
